package com.shyroke.cool.service.boke.impl;

import com.shyroke.cool.bean.LabelPO;
import com.shyroke.cool.bean.TypePO;
import com.shyroke.cool.bean.boke.TreeDto;
import com.shyroke.cool.mapper.ArticlePOMapper;
import com.shyroke.cool.mapper.LabelPOMapper;
import com.shyroke.cool.mapper.TypePOMapper;
import com.shyroke.cool.service.boke.IBokeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BokeService
 * @Desciption 博客服务层
 * @Author shyroke
 * @Date 2018/7/14 0014 18:32
 */
@Service
public class BokeService implements IBokeService {

    @Autowired
    private ArticlePOMapper articleMapper;
    @Autowired
    private LabelPOMapper labelMapper;
    @Autowired
    private TypePOMapper typeMapper;

    @Override
    public List<TreeDto> getParentFile() {
        List<TreeDto> treeDtos = null;

        /**
         * 先获取所有文章的type
         */
       List<TypePO> typePOList =  typeMapper.getTypeList();
        treeDtos = typePOList.stream().map(po->{
            TreeDto treeDto = new TreeDto();
            treeDto.setId(po.getId()+"");
            treeDto.setText(po.getTypename());
            return treeDto;
        }).collect(Collectors.toList());

        /**
         * 再计算每个顶级节点下有多少个类型label，去重
         */
        List<LabelPO> labelPOList = null;
        List<TreeDto> childNodes = null;
        TreeDto treeDto2 = null;
        for(TypePO type:typePOList){

            int typeID = type.getId();
            //根据typeID获取所有label
            labelPOList =   labelMapper.getLabelByTypeID(typeID);

           for(TreeDto treeDto:treeDtos){

               if(treeDto.getId().equals(typeID+"")){
                   childNodes = new ArrayList<>();
                   for(LabelPO label :labelPOList){
                       //根据labelID获取该label下有多少文章
                       int count = articleMapper.countByLabelID(label.getId());
                       treeDto2 = new TreeDto();
                       treeDto2.setText("   "+label.getLabelname());  //加空格防止前端样式变样
                       treeDto2.setId(label.getId()+"");
                       treeDto2.setTags(Arrays.asList(count+""));
                       treeDto2.setIcon("glyphicon glyphicon-folder-open");
                       childNodes.add(treeDto2);
                   }
                   treeDto.setNodes(childNodes);
               }

           }

        }


        return treeDtos;
    }
}
